<template>
  <div class="container">
    <div class="main">
      <div class="header">
        <el-button type="primary" @click="openDialog(null)">新建</el-button>
      </div>
      <el-table :data="filteredTableData" border class="eltable">
        <el-table-column fixed label="序号" width="80" type="index"></el-table-column>
        <el-table-column fixed label="计划状态" width="85">
          <template #default="{ row }">
            {{ dictionaryNames[row.scjh_state] }}
          </template>
        </el-table-column>
        <el-table-column fixed label="优先级" width="85">
          <template #default="{ row }">
            {{ dictionaryNames[row.scjh_yxj] }}
          </template>
        </el-table-column>
        <el-table-column fixed prop="scdd_jd" label="计划进度" width="85">
          <template #default="{ row }">
            <div class="progress-bar">
              <div class="progress-fill" :style="{ width: `${row.scdd_jd}%` }">
                {{ row.scjh_jd }}%
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column fixed prop="scjh_code" label="计划编码" width="165"></el-table-column>
        <el-table-column label="计划类型" width="85">
          <template #default="{ row }">
            {{ dictionaryNames[row.scjh_lx] }}
          </template>
        </el-table-column>
        <el-table-column label="计划性质" width="85">
          <template #default="{ row }">
            {{ dictionaryNames[row.scjh_xz] }}
          </template>
        </el-table-column>
        <el-table-column prop="ks_code" label="客户编码" width="180"></el-table-column>
        <el-table-column prop="ks_name" label="客户名称" width="180"></el-table-column>
        <el-table-column prop="ht_code" label="合同编码" width="180"></el-table-column>
        <el-table-column prop="scjh_gdsl" label="工单数量" width="180"></el-table-column>
        <el-table-column prop="cp_name" label="产品名称" width="180"></el-table-column>
        <el-table-column prop="cp_code" label="产品编码" width="180"></el-table-column>
        <el-table-column prop="cp_xh" label="产品型号" width="180"></el-table-column>
        <el-table-column prop="cp_lx" label="产品类型" width="180"></el-table-column>
        <el-table-column prop="dw_code" label="单位编码" width="180"></el-table-column>
        <el-table-column prop="dw_name" label="单位名称" width="180"></el-table-column>
        <el-table-column prop="scjh_sl" label="计划数量" width="180"></el-table-column>
        <el-table-column label="需求日期" width="180">
          <template #default="{ row }">
            {{ formatDate(row.scjh_xqrq) }}
          </template>
        </el-table-column>
        <el-table-column label="计划开工时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.scjh_kssj) }}
          </template>
        </el-table-column>
        <el-table-column prop="planned_completion_time" label="计划完工时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.scjh_jssj) }}
          </template>
        </el-table-column>
        <el-table-column prop="scdd_code" label="生产订单编码" width="180"></el-table-column>
        <el-table-column prop="create_by" label="创建人" width="180"></el-table-column>
        <el-table-column prop="create_time" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.create_time) }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="380">
          <template #default="{ row }">
            <el-button type="text" @click="Details(row)">详情</el-button>
            <el-button type="text" @click="Disassemble(row)">拆解</el-button>
            <el-button type="text" @click="Withdraw(row)">撤回</el-button>
            <el-button type="text" @click="End(row)">终止</el-button>
            <el-button type="text" @click="openDialog(row)">编辑</el-button>
            <el-button type="text" @click="deleteRow(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @current-change="handleCurrentChange" :current-page="currentPage" :page-size="pageSize"
        :total="totalItems" layout="total, prev, pager, next, jumper"></el-pagination>
    </div>
    <!-- 计划详情对话框 -->
    <el-dialog title="计划详情" v-model="dialogVisible" custom-class="plan-dialog" >
      <el-form :model="formData" label-width="100px" :rules="formRules" ref="formRef">
        <!-- 计划基本信息 -->
        <el-row>
          <el-col :span="8">
            <el-form-item label="生产计划号">
              {{ formData.scjh_code }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="优先级">
              {{ dictionaryNames[formData.scjh_yxj] || '未知' }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="计划类型">
              {{ dictionaryNames[formData.scjh_lx] || '未知' }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="计划性质">
              {{ dictionaryNames[formData.scjh_xz] || '未知' }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="产品编码">
              {{ formData.cp_code }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="产品名称">
              {{ formData.cp_name }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="产品型号">
              {{ formData.cp_xh }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="产品品牌">
              {{ formData.pp_name }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="产品类型">
              {{ formData.cp_lx }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="产品分类">
              {{ formData.cp_fl }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="客户名称">
              {{ formData.ks_code }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="合同编码">
              {{ formData.ht_code }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="交货时间">
              {{ formatDate(formData.scjh_xqrq) }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="计划开始时间">
              {{ formatDate(formData.scjh_kssj) }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="计划结束时间">
              {{ formatDate(formData.scjh_jssj) }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="任务数量">
              {{ formData.scjh_sl }}
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="备注">
              {{ formData.scjh_bz }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="完成数量">
              {{ formData.scjh_ycwsl }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="计划进度" width="85">
              <div class="progress-bar">
                <div class="progress-fill" :style="{ width: `${formData.scdd_jd}%` }">
                  {{ formData.scdd_jd }}%
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <p class="work-order-title">工单详情：</p>
      <el-table v-if="dialogVisible" :data="scgdDetailsData" border class="eltable">
        <el-table-column type="index" label="序号" width="80"></el-table-column>
        <el-table-column prop="gd_state" label="工单状态">
          <template #default="{ row }">
            {{ dictionaryNames[row.gd_state] }}
          </template>
        </el-table-column>
        <el-table-column prop="gd_jd" label="工单进度">
          <template #default="{ row }">
            <div class="progress-bar">
              <div class="progress-fill" :style="{ width: `${row.gd_jd}%` }">
                {{ row.gd_jd }}%
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="gd_jhsl" label="任务数量"></el-table-column>
      </el-table>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog">取消</el-button>
        </span>
      </template>
    </el-dialog>
    <!--新增生产计划-->
    <el-dialog :title="Mtkname" v-model="dialogVisibles"
    style="width: 900px; background-color: #fff; padding: 20px; box-shadow: 0 2px 15px rgba(0,0,0,0.15); border-radius: 30px;">
      <el-form :model="formData" label-width="100px" :rules="formRules" ref="formRef">
        <el-row>
          <el-col :span="12">
            <el-form-item label="生产计划编码:">
              <el-input v-model="formData.scjh_code" readonly></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划优先级:" prop="scjh_yxj">
              <el-select v-model="formData.scjh_yxj" placeholder="请选择">
                <el-option v-for="item in priorityOptions" :key="item.dictionary_id" :label="item.dictionary_name"
                  :value="item.dictionary_id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="计划类型:" prop="scjh_lx">
              <el-select v-model="formData.scjh_lx" placeholder="请选择">
                <el-option v-for="item in orderTypeOptions" :key="item.dictionary_id" :label="item.dictionary_name"
                  :value="item.dictionary_id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划性质:" prop="scjh_xz">
              <el-select v-model="formData.scjh_xz" placeholder="请选择">
                <el-option v-for="item in ddsz" :key="item.dictionary_id" :label="item.dictionary_name"
                  :value="item.dictionary_id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="客户编码:" prop="ks_name">
              <el-input v-model="formData.ks_name" placeholder="请输入客户编码" @click="toggleKsMTK"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同编码:">
              <el-input v-model="formData.ht_code" readonly placeholder="系统自动生成"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="产品编码:" prop="cp_code">
              <el-input v-model="formData.cp_code" placeholder="请选择产品" @click="toggleCPMTK"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品名称:" prop="cp_name">
              <el-input v-model="formData.cp_name"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="产品分类:" prop="cp_fl">
              <el-select v-model="formData.cp_fl" placeholder="请选择">
                <el-option v-for="item in cplx" :key="item.dictionary_id" :label="item.dictionary_name"
                  :value="item.dictionary_id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品型号:" prop="cp_xh">
              <el-input v-model="formData.cp_xh"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="计划数量:">
              <el-input v-model="formData.scjh_sl" placeholder="请输入订单数量"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="交货日期:" prop="scjh_xqrq">
              <el-date-picker v-model="formData.scjh_xqrq" type="datetime" placeholder="请选择交货日期"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="开始时间:" prop="scjh_kssj">
              <el-date-picker v-model="formData.scjh_kssj" type="datetime" placeholder="请选择订单开始时间"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="完成时间:" prop="scjh_jssj">
              <el-date-picker v-model="formData.scjh_jssj" type="datetime" placeholder="请选择订单完成时间"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注:">
          <el-input type="textarea" v-model="formData.scjh_bz" placeholder="请输入备注"></el-input>
        </el-form-item>
        <div style="margin-top: 20px;">
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" @click="saveForm">保存</el-button>
        </div>
      </el-form>
    </el-dialog>
    <el-dialog v-model="isCPMTKVisible" title="选择产品"
      style="height: 700px; width: 600px; background-color: #fff; padding: 20px; box-shadow: 0 2px 15px rgba(0,0,0,0.15); border-radius: 30px;">
      <CPMTK @selection-confirmed="handleSelectionConfirmed" @cancel-selection="handleCancelSelection"></CPMTK>
    </el-dialog>

    <el-dialog v-model="isKsMTKVisible" title="选择客商"
      style="height: 700px; width: 600px; background-color: #fff; padding: 20px; box-shadow: 0 2px 15px rgba(0,0,0,0.15); border-radius: 30px;">
      <KsMTK @selection-confirmed="handleSelectionConfirmeds" @cancel-selection="handleCancelSelections"></KsMTK>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed, watchEffect } from 'vue';
import { ElMessage } from 'element-plus';
import axios from 'axios';
import CPMTK from '../MTK/CPMTK.vue';
import KsMTK from '../MTK/KsMTK.vue';

// 封装请求函数
const request = async (url) => {
  try {
    const response = await axios.get(url);
    return response.data;
  } catch (error) {
    console.error(`请求 ${url} 失败:`, error);
    ElMessage.error(`请求失败: ${error.message}`);
    throw error;
  }
};

export default {
  components: { CPMTK, KsMTK },
  setup() {
    const tableData = ref([]);
    const selectedFilter = ref('');
    const searchTable = ref('');
    const currentPage = ref(1);
    const formRef = ref(null); // 表单引用
    const pageSize = ref(10);
    const totalItems = ref(0);
    const dialogVisible = ref(false);
    const dialogVisibles = ref(false);
    const dictionaryNames = ref({}); // 存储字典名称
    const formData = ref({});
    const isCPMTKVisible = ref(false);
    const isKsMTKVisible = ref(false);
    const Mtkname = ref();
    const scgdDetailsData = ref({});
    const cp_code = ref([]);
    const priorityOptions = ref({}); //订单优先级
    const orderTypeOptions = ref({}); //订单类型  
    const ddsz = ref({}); //订单性质
    const cplx = ref({})
    const fetchData = async () => {
      try {
        const data = await request('/api/Mes_scjh/GetMes_scjh');
        tableData.value = data;
        totalItems.value = data.length;
        const res = await request('/api/Dict/GetOneDict?id=12')
        orderTypeOptions.value = res;
        const ress = await request('/api/Dict/GetOneDict?id=14')
        priorityOptions.value = ress;
        const resss = await request('/api/Dict/GetOneDict?id=13')
        ddsz.value = resss;
        const ressss = await request('/api/Dict/GetOneDict?id=7')
        cplx.value = ressss;
      } catch (error) {
        console.error('Error fetching tableData:', error);
      }
    };

    const filteredTableData = computed(() => {
      totalItems.value = tableData.value.length;
      const start = (currentPage.value - 1) * pageSize.value;
      return tableData.value.slice(start, start + pageSize.value);
    });
    //终止
    const End = async (row) => {
      try {
        // 获取订单状态  
        const state = await request(`/api/Mes_SCGD/GetStatus?scjh_code=${row.scjh_code}`);

        // 判断状态数组中是否有值等于 58   已投产 
        const hasValue55 = state.includes(58);

        if (hasValue55) {
          ElMessage.error('计划已投产不可操作');
          return;
        }
        // 终止生产计划的 URL  
        const deleteUrl = `/api/Mes_SCjh/UpdateStatus?scjh_code=${row.scjh_code}&state=51&update_by=${sessionStorage.getItem('u')}&scdd_code="1"`;
        // 更新工单状态的 URL  
        const url = `/api/Mes_SCGD/UpdateStatus?scgd_code=1&state=51&update_by=${sessionStorage.getItem('u')}&scjh_code=${row.scjh_code}`;
        // 使用 Promise.all 确保两个请求都成功  
        await Promise.all([
          axios.put(deleteUrl, {}),
          axios.put(url, {})
        ]);

        // 两个请求都成功后提示  
        ElMessage.success('已终止该生产计划以及它的生产工单!');

        // 刷新数据  
        fetchData();
      } catch (error) {
        // 错误处理  
        ElMessage.error('操作失败: ' + error.message);
      }
    }
    //撤回
    const Withdraw = async (row) => {
      // 获取订单状态  
      const state = await request(`/api/Mes_SCGD/GetStatus?scjh_code=${row.scjh_code}`);

      // 判断状态数组中是否有值等于 已投产
      const hasValue55 = state.includes(58);

      if (hasValue55) {
        ElMessage.error('计划已分解不可操作');
        return;
      }
      // 更新订单状态  
      const url = `/api/Mes_SCjh/UpdateStatus?scjh_code=${row.scjh_code}&state=50&update_by=${sessionStorage.getItem('u')}&scdd_code="1"`;
      try {
        await axios.put(url, {});
        // 删除生产计划  
        const deleteUrl = `/api/Mes_SCGD/DeleteScgd?scgd_code=${row.scjh_code}`;
        await axios.delete(deleteUrl);
        ElMessage.success('撤回该生产计划!');
        fetchData();
      } catch (error) {
        ElMessage.error('操作失败: ' + error.message);
      }
    }
    //点击拆解
    const Disassemble = async (row) => {
      const productDetails = await request(`/api/Mbd_BOMxq/GetMbd_BOMxg?bomcode=${row.bom_code}`);
      scgdDetailsData.value = productDetails;
      if (row.scjh_state == 55) {
        ElMessage.error('该计划已拆解');
      } else {
        // 循环发送每个产品详情数据到后端
        for (let i = 0; i < scgdDetailsData.value.length; i++) {
          const gdCode = generateGDCode();
          const product = scgdDetailsData.value[i];

          // 发送 AddMesScjh 请求
          axios.post('/api/Mes_SCGD/AddMes_SCGD', {
            gd_yxj: row.scjh_yxj,
            gd_code: gdCode,
            gd_name: "生产" + product.wl_name,
            cp_code: product.wl_code,
            cp_name: product.wl_name,
            cp_xh: product.wl_xh,
            cp_lx: product.wl_lx,
            cp_fl: product.wl_fl,
            pp_code: row.pp_code,
            pp_name: row.pp_name,
            dw_code: product.dw_code,
            dw_name: product.dw_name,
            ks_code: row.ks_code,
            ks_name: row.ks_name,
            ht_code: row.ht_code,
            bom_code: product.bom_code,
            gd_jhsl: row.scjh_sl,
            gd_sjscsl: 0,
            gd_xqrq: new Date(row.scjh_xqrq),
            gd_jhkgsj: new Date(row.scjh_kssj),
            gd_jhwgsj: new Date(row.scjh_jssj),
            gd_bz: row.scjh_bz,
            scjh_code: row.scjh_code,
            create_by: sessionStorage.getItem('u'),
            ht_code: row.ht_code
          })
        }
        const urls = `/api/Mes_SCjh/UpdateMesScjhgd?gdsl=${scgdDetailsData.value.length}&scjhcode=${row.scjh_code}`;
        const url = `/api/Mes_SCjh/UpdateStatus?scjh_code=${row.scjh_code}&state=55&update_by=${sessionStorage.getItem('u')}&scdd_code="1"`;
        // 发起 POST 请求
        await axios.put(url, {});
        await axios.put(urls, {});
        // 处理响应
        ElMessage.success('拆解成功!');
        fetchData();
      }
    };
    const Details = async (row) => {
      formData.value = { ...row };
      try {
        const productDetails = await request(`/api/Mes_SCGD/GetMes_scjhcode?scjh_code=${row.scjh_code}`);
        scgdDetailsData.value = Array.isArray(productDetails) ? productDetails : [];
      } catch (error) {
        console.error('Error fetching product details:', error);
      }
      dialogVisible.value = true;
    };
    // 保存表单
    const saveForm = async () => {
      await formRef.value.validate((valid) => {
        if (valid) {
          if (formData.value.scjh_id) {
            // 修改操作
            axios.put('/api/Mes_scjh/UpdateMesScjh', {
              scjh_yxj: parseInt(formData.value.scjh_yxj),
              scjh_code: formData.value.scjh_code,
              scjh_lx: parseInt(formData.value.scjh_lx),
              scjh_xz: parseInt(formData.value.scjh_xz),
              ks_code: formData.value.ks_code,
              ks_name: formData.value.ks_name,
              ht_code: formData.value.ht_code,
              cp_name: formData.value.cp_name,
              cp_code: formData.value.cp_code,
              cp_xh: formData.value.cp_xh,
              cp_lx: parseInt(formData.value.cp_lx),
              cp_fl: parseInt(formData.value.cp_fl),
              pp_code: formData.value.pp_code,
              pp_name: formData.value.pp_name,
              dw_code: formData.value.dw_code,
              dw_name: formData.value.dw_name,
              bom_code: formData.value.bom_code,
              scjh_sl: parseInt(formData.value.scjh_sl),
              scjh_kssj: new Date(formData.value.scjh_kssj),
              scjh_jssj: new Date(formData.value.scjh_jssj),
              scjh_xqrq: new Date(formData.value.scjh_xqrq),
              scjh_bz: formData.value.scjh_bz,
              update_by: sessionStorage.getItem('u'),
              update_time: new Date()
            })
              .then(response => {
                ElMessage.success('修改成功');
                dialogVisibles.value = false; // 关闭对话框
                fetchData();
              })
              .catch(error => {
                ElMessage.error('修改失败：' + error.message);
              });
          } else {
            console.log(formData.value)
            axios.post('/api/Mes_scjh/AddMesScjh', {
              scjh_id: 0,
              scjh_state: 56,
              scjh_yxj: parseInt(formData.value.scjh_yxj),
              scjh_jd: 0,
              scjh_code: formData.value.scjh_code,
              scjh_lx: parseInt(formData.value.scjh_lx),
              scjh_xz: parseInt(formData.value.scjh_xz),
              ks_code: formData.value.ks_code,
              ks_name: formData.value.ks_name,
              ht_code: formData.value.ht_code,
              scjh_gdsl: 0,
              cp_name: formData.value.cp_name,
              cp_code: formData.value.cp_code,
              cp_xh: formData.value.cp_xh,
              cp_lx: parseInt(formData.value.cp_lx),
              cp_fl: parseInt(formData.value.cp_fl),
              pp_code: formData.value.pp_code,
              pp_name: formData.value.pp_name,
              dw_code: formData.value.dw_code,
              dw_name: formData.value.dw_name,
              bom_code: formData.value.bom_code,
              scjh_sl: parseInt(formData.value.scjh_sl),
              scjh_yscsl: 0,
              scjh_kssj: new Date(formData.value.scjh_kssj),
              scjh_jssj: new Date(formData.value.scjh_jssj),
              scjh_xqrq: new Date(formData.value.scjh_xqrq),
              scjh_bz: formData.value.scjh_bz,
              scjh_fjzt: 0,
              scdd_code: 'null',
              create_by: sessionStorage.getItem('u'),
              create_time: new Date(),
              update_by: 1,
              update_time: new Date()
            })
              .then(response => {
                ElMessage.success('新增成功');
                dialogVisibles.value = false; // 关闭对话框
                fetchData();
              })
              .catch(error => {
                ElMessage.error('新增失败：' + error.message);
              });
          }
        } else {
          // 表单验证失败，提示用户
          ElMessage.error('表单验证失败，请检查输入');
        }
      });
    };
    const reset = () => {
      selectedFilter.value = '';
      searchTable.value = '';
      currentPage.value = 1;
    };
    //删除
    const deleteRow = (row) => {
      if (row.scjh_state) {
        // const deleteUrl = `/api/Mes_scjh/DeleteScjh?scdd_code=${row.scdd_code}`;
        // axios.delete(deleteUrl);
      }
    };
    //新增编辑计划
    const openDialog = async (row) => {
      formData.value = []
      Mtkname.value = row ? '编辑生产计划' : '新增生产计划';
      if (row) {
        if (row.scjh_state == 55) {
          ElMessage.error('该计划已经分解禁止编辑');
        } else {
          Object.assign(formData.value, row);
          dialogVisibles.value = true;
        }
      } else {
        Object.assign(formData.value, {
          scjh_code: generateScjhCode(),
          ht_code: generateHTCode()
        });
        dialogVisibles.value = true;
      }
    };
    const handleCurrentChange = (page) => {
      currentPage.value = page;
    };

    const formatDate = (dateString) => {
      if (!dateString) return '';
      const date = new Date(dateString);
      return `${date.getFullYear()}/${(date.getMonth() + 1).toString().padStart(2, '0')}/${date.getDate().toString().padStart(2, '0')}`;
    };

    const formatDictionaryName = async (dictionaryId) => {
      if (!dictionaryId) return '';
      if (dictionaryNames.value[dictionaryId]) {
        return dictionaryNames.value[dictionaryId];
      }
      try {
        const response = await axios.get(`/api/Dict/GetName?dictionary_id=${dictionaryId}`);
        dictionaryNames.value[dictionaryId] = response.data;
        return response.data;
      } catch (error) {
        console.error(`获取字典名称时出错: ${error.message}`);
        return '';
      }
    };
    //生成生产计划code
    function generateScjhCode() {
      const prefix = 'SCJH';
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');

      // 生成 0 - 9999 之间的随机整数
      const randomNum = Math.floor(Math.random() * 10000);
      // 将随机数格式化为四位字符串，不足四位时前面补 0
      const sequenceNumber = String(randomNum).padStart(4, '0');

      return `${prefix}${year}${month}${day}${sequenceNumber}`;
    }
    //生成生产工单code
    function generateGDCode() {
      const prefix = 'GD';
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');

      // 生成 0 - 9999 之间的随机整数
      const randomNum = Math.floor(Math.random() * 10000);
      // 将随机数格式化为四位字符串，不足四位时前面补 0
      const sequenceNumber = String(randomNum).padStart(4, '0');

      return `${prefix}${year}${month}${day}${sequenceNumber}`;
    }
    //生成合同code
    function generateHTCode() {
      const prefix = 'HT';
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');

      // 生成 0 - 9999 之间的随机整数
      const randomNum = Math.floor(Math.random() * 10000);
      // 将随机数格式化为四位字符串，不足四位时前面补 0
      const sequenceNumber = String(randomNum).padStart(4, '0');

      return `${prefix}${year}${month}${day}${sequenceNumber}`;
    }
    // 监听表格数据变化，更新字典名称
    watchEffect(() => {
      filteredTableData.value.forEach((row) => {
        if (row.scjh_state) {
          formatDictionaryName(row.scjh_state);
        } if (row.scjh_yxj) {
          formatDictionaryName(row.scjh_yxj);
        }
        if (row.scjh_lx) {
          formatDictionaryName(row.scjh_lx);
        }
        if (row.scjh_xz) {
          formatDictionaryName(row.scjh_xz);
        }
      });
      if (Array.isArray(scgdDetailsData.value)) {
        scgdDetailsData.value.forEach((row) => {
          if (row.gd_state) {
            formatDictionaryName(row.gd_state);
          }
        });
      }
    });
    // 选择产品  
    const handleSelectionConfirmed = async (ids) => {
      try {
        // 将选中的 ID 赋值给表单数据中的 cp_code
        formData.value.cp_code = String(ids);

        // 构建请求 URL，使用 URLSearchParams 更安全地处理参数
        const baseUrl = '/api/BD_CP/GetBD_CPcp_code';
        const params = new URLSearchParams({
          cp_code: formData.value.cp_code
        });
        const url = `${baseUrl}?${params.toString()}`;

        // 发起异步请求并等待响应
        const response = await axios.get(url);

        // 从响应数据中提取产品名称并赋值给表单数据
        formData.value.cp_name = response.data.cp_name;
        formData.value.cp_fl = response.data.cp_fl;
        formData.value.cp_xh = response.data.cp_xh;
        formData.value.cp_lx = response.data.cp_lx,
          formData.value.pp_code = response.data.pp_code,
          formData.value.dw_code = response.data.dw_code,
          formData.value.dw_name = response.data.dw_name,
          formData.value.bom_code = response.data.bom_code,

          // 关闭选择产品的对话框
          isCPMTKVisible.value = false;
      } catch (error) {
        console.error('获取产品信息时出错:', error);
      }
    };
    //关闭产品模态框
    const handleCancelSelection = () => {
      isCPMTKVisible.value = false;
    };
    //选择客商
    const handleSelectionConfirmeds = (data) => {
      formData.value.ks_code = data.id;
      formData.value.ks_name = data.name;
      isKsMTKVisible.value = false;
    };
    //关闭客商模态框
    const handleCancelSelections = () => {
      isKsMTKVisible.value = false;
    };
    // 关闭对话框
    const closeDialog = () => {
      dialogVisible.value = false;
      dialogVisibles.value = false;
      formData.value = {};
    };
    //显示产品模态框
    const toggleCPMTK = () => {
      isCPMTKVisible.value = !isCPMTKVisible.value; // 切换显示状态  
    };

    //显示客商模态框
    const toggleKsMTK = () => {
      isKsMTKVisible.value = !isCPMTKVisible.value; // 切换显示状态  
    };
    fetchData();

    return {
      tableData,
      selectedFilter,
      searchTable,
      currentPage,
      pageSize,
      totalItems,
      filteredTableData,
      reset,
      deleteRow,
      handleCurrentChange,
      formatDate,
      dictionaryNames,
      dialogVisible,
      Details,
      formData,
      scgdDetailsData,
      Disassemble,
      generateGDCode,
      dialogVisibles,
      openDialog,
      closeDialog,
      toggleCPMTK,
      toggleKsMTK,
      handleCancelSelection,
      handleSelectionConfirmeds,
      handleSelectionConfirmed,
      handleCancelSelections,
      isCPMTKVisible,
      isKsMTKVisible,
      Mtkname,
      cp_code,
      priorityOptions,
      orderTypeOptions,
      ddsz,
      cplx,
      generateScjhCode,
      saveForm,
      generateHTCode,
      formRef,
      Withdraw,
      End
    };
  },
};
</script>

<style>
.container {
  display: flex;
  gap: 20px;
  height: 95%;
}

.main {
  width: 80%;
  flex: 1;
  height: 100%;
}

.header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
}

.eltable {
  height: 95%;
}

.plan-dialog {
  border-radius: 30px;
  width: 40%;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

/* 对话框头部样式 */
.plan-dialog .el-dialog__header {
  background-color: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
  padding: 16px 20px;
}

.plan-dialog .el-dialog__title {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

/* 对话框主体样式 */
.plan-dialog .el-dialog__body {
  padding: 20px;
}

/* 表单行样式 */
.plan-dialog .el-row {
  margin-bottom: 12px;
}

/* 表单项标签样式 */
.plan-dialog .el-form-item__label {
  font-weight: 500;
  color: #606266;
  font-size: 14px;
}

/* 表单项内容样式 */
.plan-dialog .el-form-item__content {
  font-size: 14px;
  color: #303133;
}

/* 工单详情标题样式 */
.work-order-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-top: 20px;
  margin-bottom: 12px;
}

.progress-bar {
  width: 100%;
  height: 20px;
  background-color: #e0e0e0;
  border-radius: 15px;
  overflow: hidden;
  position: relative;
}

.progress-fill {
  height: 100%;
  background-color: #409eff;
  border-radius: 15px 0 0 15px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: rgb(0, 0, 0);
  font-weight: bold;
  transition: width 0.3s;
}

/* 对话框底部样式 */
.dialog-footer {
  text-align: right;
  padding: 16px 20px;
  border-top: 1px solid #e4e7ed;
}

.dialog-footer .el-button {
  font-size: 14px;
}
</style>